# ------------------------------------------------------------------------------------------------
### Generate Table 4: Effects by sum of treatment levels
# ------------------------------------------------------------------------------------------------

# Load data 
load("../data/results/sdid_results.Rda")

# Filter and prepare data - need to handle sum_level filtering differently
filtered_results <- sdid_results %>%
  filter(
    outcome %in% c("Overall Turnout", "Party Turnout"),
    party %in% c("Opposition", "Overall Turnout", "Law and Justice (PiS)"),
    sum_level != "Any Level",  # This is the key filter - exclude "Any Level" to get specific levels
    sum_type == "Any Type",
    level == "Any Level",
    type == "Any Type",
    control_sample == "notyettreated",
    no300k_sample == "Full Sample",
    noproposed_sample == "Full Sample"
  ) %>%
  mutate(
    outcome = case_when(
      outcome == "Party Turnout" & party == "Opposition" ~ "Opposition Turnout",
      outcome == "Party Turnout" & party == "Law and Justice (PiS)" ~ "Government Turnout",
      TRUE ~ outcome
    ),
    outcome = factor(outcome, levels = c("Overall Turnout", "Opposition Turnout", "Government Turnout")),
    sum_level = factor(sum_level, levels = c("One Level", "Two Levels", "Three Levels"))
  ) %>%
  arrange(outcome, sum_level)

# Generate and save table
latex_table <- create_latex_table(
  filtered_results,
  group_var = "outcome",
  row_var = "sum_level",
  caption = "Synthetic Difference-in-Differences Estimates by Sum Level of Treatment",
  label = "tab:sdid_sum_of_levels",
  col_names = c("Outcome", "Sum Level", "Estimate (SE)", "N")
)

save_table(latex_table, "../output/tables/table4.txt")
